#!/usr/bin/env python3
import os
import re
import sys

def main():
    script_dir = os.path.dirname(os.path.abspath(__file__))
    
    html_path = os.path.join(script_dir, "ghost_site.html")
    output_path = os.path.join(script_dir, "../../include/managers/ghost_esp_site.h")
    
    os.makedirs(os.path.dirname(output_path), exist_ok=True)
    
    try:
        from htmlmin import minify as html_minify
        from csscompressor import compress as css_compress
        import jsmin
    except ImportError:
        print("Error: Required libraries not found. Installing them now...")
        install_dependencies()
        from htmlmin import minify as html_minify
        from csscompressor import compress as css_compress
        import jsmin
    
    try:
        with open(html_path, 'r', encoding='utf-8') as f:
            html_content = f.read()
    except Exception as e:
        print(f"Error reading HTML file: {e}")
        sys.exit(1)
    
    print(f"Original HTML size: {len(html_content)} bytes")
    
    def minify_css(match):
        css_content = match.group(1)
        try:
            minified = css_compress(css_content)
            return f"<style>{minified}</style>"
        except Exception as e:
            print(f"Warning: Error minifying CSS: {e}")
            return match.group(0)
    
    html_content = re.sub(r'<style>(.*?)</style>', minify_css, html_content, flags=re.DOTALL)
    
    def minify_js(match):
        js_content = match.group(1)
        try:
            minified = jsmin.jsmin(js_content)
            return f"<script>{minified}</script>"
        except Exception as e:
            print(f"Warning: Error minifying JavaScript: {e}")
            return match.group(0)
    
    html_content = re.sub(r'<script>(.*?)</script>', minify_js, html_content, flags=re.DOTALL)
    
    try:
        minified_html = html_minify(html_content, 
                                    remove_comments=True,
                                    remove_empty_space=True,
                                    remove_all_empty_space=False,
                                    reduce_boolean_attributes=True)
    except Exception as e:
        print(f"Warning: Error minifying HTML: {e}")
        print("Using original HTML content...")
        minified_html = html_content
    
    print(f"Minified HTML size: {len(minified_html)} bytes")
    
    minified_binary = minified_html.encode('utf-8') + b'\0'
    
    bytes_array = [f"0x{b:02X}" for b in minified_binary]
    
    bytes_per_line = 20
    lines = []
    for i in range(0, len(bytes_array), bytes_per_line):
        chunk = bytes_array[i:i+bytes_per_line]
        lines.append("  " + ", ".join(chunk) + ",")
    
    if lines:
        lines[-1] = lines[-1][:-1]
    
    header_content = f"""/* Generated by html_to_header.py, do not edit manually */

/* Contents of file ghost_site.html */
const long int ghost_site_html_size = {len(minified_binary) - 1}UL + 1;
const unsigned char ghost_site_html[{len(minified_binary) - 1}UL + 1] = {{
{os.linesep.join(lines)}
}};
"""
    
    try:
        with open(output_path, 'w', encoding='utf-8') as f:
            f.write(header_content)
        print(f"Successfully generated header file: {output_path}")
        print(f"Minified size: {len(minified_binary) - 1} bytes (plus null terminator)")
        percentage = (1 - (len(minified_binary) / len(html_content.encode('utf-8')))) * 100
        print(f"Size reduction: {percentage:.2f}%")
    except Exception as e:
        print(f"Error writing header file: {e}")
        sys.exit(1)

def install_dependencies():
    import subprocess
    
    dependencies = ["htmlmin", "csscompressor", "jsmin"]
    
    try:
        for dep in dependencies:
            print(f"Installing {dep}...")
            subprocess.check_call(
                [sys.executable, "-m", "pip", "install", dep]
            )
        print("All dependencies installed successfully!")
    except subprocess.CalledProcessError as e:
        print(f"Error installing dependencies: {e}")
        print("Please install the following manually:")
        print("  pip install htmlmin csscompressor jsmin")
        sys.exit(1)

if __name__ == "__main__":
    main() 